<template>
	<view class="fast-select-radio">
		<scroll-view 
			scroll-y 
			class="fast-select-key"
			:scroll-into-view="indexKey"
			scroll-with-animation
		>
			<view 
				class="fast-select-item" 
				:class="ik == item ? 'selected' : ''"
				:id="item"
				v-for="(item, i) in keys" 
				@click.stop="selectKey(item, i)"
			>
			{{ item }}
			</view>
		</scroll-view>
		<scroll-view 
			scroll-y
			class="fast-select-label"
			@scroll="handleScroll"
			:scroll-into-view="conKey"
			scroll-with-animation
		>
			<view 
				class="fast-select-item" 
				:class="value[0] == i ? 'selected' : ''"
				v-for="(item, i) in data"
				:id="'con' + item[index]"
				:indexKey="item[index]"
				@click.stop="onChange(item, i)"
			>
			{{ item[label] }}
			</view>
		</scroll-view>
		
	</view>
</template>

<script>
	export default {
		props: {
			value: {
				type: Array,
				default: () => {
					return []
				}
			},
			label: {
				type: String,
				default: ''
			},
			index: {
				type: String,
				default: 'key'
			},
			//下拉框数据源
			data: {
				type: Array,
				default: () => {
					return []
				}
			}
		},
		computed:{
			keys(){
				const keys = this.data.map(item => item[this.index]);
				return Array.from(new Set(keys))
			},
			ik(){
				if(!this.indexKey){
					if(this.data && this.data.length > 0){
						return this.data[0][this.index]
					}
				}
				return this.indexKey;
			}
		},
		data() {
			return {
				indexKey: '',
				conKey: ''
			}
		},
		methods: {
			onChange(item, index){
				this.$set(this.value, 0, index)
				this.$emit('input', this.value)
				this.$emit('change', item, index)
			},
			handleScroll(e) {
				const scrollTop = e.detail.scrollTop; // 当前滚动条的位置
				const label = document.getElementsByClassName('fast-select-label')[0]
				const items = label.getElementsByClassName('fast-select-item')
				
				const scroll = label.getBoundingClientRect();
				const itemArr = Array.from(items).sort((a, b) => a.top - b.top);
				const firstVisibleItem = itemArr.find(item => {
					const rect = item.getBoundingClientRect();
					// 检查元素是否在div的视口内
					return (
						rect.top >= scroll.top
					);
				});
				if (firstVisibleItem) {
					this.indexKey = firstVisibleItem.getAttribute('indexKey')
				}
			},
			selectKey(item, i){
				this.conKey = 'con' + item
				this.indexKey = item
			}
			
		}
	}
</script>

<style lang="less" scoped>
	.fast-select-radio{
		height: 60vw;
		display: flex;
		
		.fast-select-key{
			height: 100%;
			font-size: 0.7em;
			width: 10%;
		}
		
		.fast-select-label{
			height: 100%;
			width: 90%;
		}
		
		
		.fast-select-item{
			text-align: center;
		}
		
		.selected{
			color: #007AFF;
		}
	}

</style>
